﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Networking;
using Sa1;

public class NetworkPanel : MonoBehaviour {

	public NetworkManager manager;

	public Button showButton;
	public Image configsPanel;

	public InputField inputField;
	public Button hostButton;
	public Button clientButton;
	public Button closeButton;

	// Use this for initialization
	void Start () {
		Gs.onEvent(this.configsPanel).onClick = exitPanel;
		Gs.onEvent(this.showButton).onClick = showPanel;
		Gs.onEvent(this.hostButton).onClick = startHost;
		Gs.onEvent(this.clientButton).onClick = startClient;
		Gs.onEvent(this.closeButton).onClick = stopNetwork;
	}

	// Update is called once per frame
	void Update () {
		if (!string.IsNullOrEmpty(inputField.text)) {
			manager.networkAddress = inputField.text;
		}
	}

	public void exitPanel(GameObject go) {
		showButton.gameObject.SetActive(true);
		configsPanel.gameObject.SetActive(false);
	}

	public void showPanel(GameObject go) {
		showButton.gameObject.SetActive(false);
		configsPanel.gameObject.SetActive(true);
	}

	public void startHost(GameObject go) {
		if (networkNotActive) manager.StartHost();
		exitPanel(go);
	}

	public void startClient(GameObject go) {
		if (networkNotActive) manager.StartClient();
		exitPanel(go);
	}

	public void stopNetwork(GameObject go) {
		if (NetworkServer.active || NetworkClient.active) manager.StopHost();
	}

	private bool networkNotActive {
		get {return !NetworkClient.active && !NetworkServer.active && manager.matchMaker == null;}
	}
}
